package com.atguigu.juc.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


class Ticket //资源类 ,类就是一个实体对象的高度抽象封装体(类 = field + method)
{
    int number = 50;

    Lock lock = new ReentrantLock();//可重入锁+独占锁+默认非公平锁

    public void sale()
    {
        lock.lock();
        try
        {
            if(number > 0)
            {
                System.out.println(Thread.currentThread().getName()+"\t"+"卖出第:"+(number--)+"\t"+"还剩下"+number);
            }
        }finally {
            lock.unlock();
        }
    }


}
/**
 * @auther zzyy
 * @create 2021-06-17 21:32
 */
public class SaleTicketThreadPoolDemo
{
    public static void main(String[] args)
    {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        Ticket ticket = new Ticket();

        try
        {
            for (int i = 1; i <=55; i++) threadPool.submit(() -> ticket.sale());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}
